package com.zxf.basic.base

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * @author zjc
 * @date 2023/10/31
 */
abstract class VmBindingFragment<VM: BaseViewModel, VB: ViewBinding>(private val inflater: (LayoutInflater) -> VB) : BindingFragment<VB>(inflater) {
    lateinit var vm: VM
        private set

    /**
     * 用了hilt，就不能用这种方式初始化了
     */
    var initViewModel: Boolean = true

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        if (initViewModel) {
            initViewModel()
        }
        super.onViewCreated(view, savedInstanceState)
    }

    private fun initViewModel() {
        val argument = (this.javaClass.genericSuperclass as ParameterizedType).actualTypeArguments
        vm = ViewModelProvider(this).get(argument[0] as Class<VM>)
    }

}